﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Security;
using Core.Library;
using DataObject;
using DataObject.Members;
using DataObject.Ref;
using OAuth;

namespace Event
{
    public partial class LoginMing : System.Web.UI.Page
    {
        public string strAuthen = Util.GetAuthenUrl();
        public string user = String.Empty;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                try
                {
                    if (!String.IsNullOrEmpty(Request.QueryString["oauth_token"]))
                    {
                        string timeStamp = "";
                        string nonce = "";
                        string resultAccessToken = connectMing_Step3(out timeStamp, out nonce);
                        connectMing_Step4(resultAccessToken, timeStamp, nonce);
                    }
                    else
                    {
                        string return_oauth_token = "";
                        string timeStamp = "";
                        string nonce = "";
                        return_oauth_token = connectMing_Step1(out timeStamp, out nonce);
                        connectMing_Step2(return_oauth_token, timeStamp, nonce);
                    }
                }
                catch (Exception ex) { }
            }
        }
        protected void formsAuthenticationTicket()
        {
            FormsIdentity ident = User.Identity as FormsIdentity;
            if (ident != null)
            {
                FormsAuthenticationTicket ticket = ident.Ticket;
                string userDataString = ticket.UserData;
                string[] userData = userDataString.Split("|".ToCharArray());

                Response.Write("<script>parent.MingInfo();</script>");
            }
        }

        protected string connectMing_Step1(out string timeStamp, out string nonce)
        {
            string normalizedUrl;
            string normalizedRequestParameters;
            //string url_domain = Request.ServerVariables("SERVER_NAME");
            /*Step1 RequestUrl*/
            OAuthBase myOAuth = new OAuthBase();
            timeStamp = myOAuth.GenerateTimeStamp();
            nonce = myOAuth.GenerateNonce();
            Uri requestUrl = new Uri(Util.GetAppSettingValue("bigMingRequestUrl"));
            string currentPageUrl = "";
            if (Request.ServerVariables["HTTPS"].ToString() == "")
            {
                currentPageUrl = Request.ServerVariables["SERVER_PROTOCOL"].ToString().ToLower().Substring(0, 4).ToString() + "://" + Request.ServerVariables["SERVER_NAME"].ToString() + ":" + Request.ServerVariables["SERVER_PORT"].ToString() + Request.ServerVariables["SCRIPT_NAME"].ToString();
            }
            else
            {
                currentPageUrl = Request.ServerVariables["SERVER_PROTOCOL"].ToString().ToLower().Substring(0, 5).ToString().Replace("/", "") + "://" + Request.ServerVariables["SERVER_NAME"].ToString() + ":" + Request.ServerVariables["SERVER_PORT"].ToString() + Request.ServerVariables["SCRIPT_NAME"].ToString();
            }

            string signature = myOAuth.MingSignature(requestUrl, Util.GetAppSettingValue("mingConsumerKey"), Util.GetAppSettingValue("mingConsumerSecret"),
                currentPageUrl, "GET", timeStamp, nonce, "", "", "", OAuth.OAuthBase.SignatureTypes.HMACSHA1, out normalizedUrl,
                                                        out normalizedRequestParameters);

            string strGenURL = normalizedUrl + "?" + normalizedRequestParameters + "&oauth_signature=" + myOAuth.UrlEncode(signature);
            string return_oauth_token = Util.getData(strGenURL);
            return return_oauth_token;
        }
        protected void connectMing_Step2(string return_oauth_token, string timeStamp, string nonce)
        {
            string normalizedUrl;
            string normalizedRequestParameters;
            string currentPageUrl = "";
            if (Request.ServerVariables["HTTPS"].ToString() == "")
            {
                currentPageUrl = Request.ServerVariables["SERVER_PROTOCOL"].ToString().ToLower().Substring(0, 4).ToString() + "://" + Request.ServerVariables["SERVER_NAME"].ToString() + ":" + Request.ServerVariables["SERVER_PORT"].ToString() + Request.ServerVariables["SCRIPT_NAME"].ToString();
            }
            else
            {
                currentPageUrl = Request.ServerVariables["SERVER_PROTOCOL"].ToString().ToLower().Substring(0, 5).ToString() + "://" + Request.ServerVariables["SERVER_NAME"].ToString() + ":" + Request.ServerVariables["SERVER_PORT"].ToString() + Request.ServerVariables["SCRIPT_NAME"].ToString();
            }

            //currentPageUrl = currentPageUrl.Replace("afamily.vn:80", "afamily.vn");

            OAuthBase myOAuth = new OAuthBase();
            Uri authenticateUrl = new Uri(Util.GetAppSettingValue("bigMingAuthenticateUrl"));
            string token = "";
            string tokenSercret = "";
            string result1 = return_oauth_token;
            string[] arrResult1 = result1.Split('&');
            if (arrResult1.Length > 1)
            {
                token = arrResult1[0].Substring(arrResult1[0].IndexOf('=') + 1);
                tokenSercret = arrResult1[1].Substring(arrResult1[1].IndexOf('=') + 1);
            }
            Session["tokenSercret"] = tokenSercret;

            string signature = myOAuth.MingSignature(authenticateUrl, Util.GetAppSettingValue("mingConsumerKey"), Util.GetAppSettingValue("mingConsumerSecret"), currentPageUrl, "GET", timeStamp, nonce, "",
                HttpUtility.UrlDecode(token), HttpUtility.UrlDecode(tokenSercret), OAuth.OAuthBase.SignatureTypes.HMACSHA1,
                out normalizedUrl, out normalizedRequestParameters);
            string strGenURL1 = normalizedUrl + "?" + normalizedRequestParameters + "&no_connect=1&oauth_signature=" + signature;
            string strGenURL2 = normalizedUrl + "?oauth_token=" + token;
            Response.Redirect(strGenURL2);
            string result = string.Empty;

            #region Khong can thiet, co the dung khi Ming thay doi phien ban
            WebRequest wrq = WebRequest.Create(strGenURL2);
            WebResponse wrs = wrq.GetResponse();

            StreamReader strdr = new StreamReader(wrs.GetResponseStream(), Encoding.UTF8);
            result = strdr.ReadToEnd();
            strdr.Close();
            wrs.Close();
            Response.Write(result);
            #endregion
        }

        protected string connectMing_Step3(out string timeStamp, out string nonce)
        {
            string normalizedUrl;
            string normalizedRequestParameters;

            OAuthBase myOAuth = new OAuthBase();
            timeStamp = myOAuth.GenerateTimeStamp();
            nonce = myOAuth.GenerateNonce();
            Uri uriAccessUrl = new Uri(Util.GetAppSettingValue("bigMingAccessUrl"));
            string oauth_token = Request.QueryString["oauth_token"];
            if (oauth_token == null) oauth_token = Request.Form["oauth_token"];
            string oauth_verifier = Request.QueryString["oauth_verifier"];
            if (oauth_verifier == null) oauth_verifier = Request.Form["oauth_verifier"];
            if (oauth_verifier.Contains("?")) oauth_verifier = oauth_verifier.Substring(0, oauth_verifier.IndexOf('?'));

            string signature = myOAuth.MingSignature(uriAccessUrl, Util.GetAppSettingValue("mingConsumerKey"), Util.GetAppSettingValue("mingConsumerSecret"), "", "GET", timeStamp, nonce, oauth_verifier,
                HttpUtility.UrlDecode(oauth_token), HttpUtility.UrlDecode(Session["tokenSercret"].ToString()), OAuth.OAuthBase.SignatureTypes.HMACSHA1,
                out normalizedUrl, out normalizedRequestParameters);

            string strGenURL = normalizedUrl + "?" + normalizedRequestParameters + "&oauth_signature=" + myOAuth.UrlEncode(signature);
            string resultAccessToken = Util.getData(strGenURL);
            return resultAccessToken;
        }

        protected void connectMing_Step4(string resultAccessToken, string timeStamp, string nonce)
        {
            string token = "";
            string tokenSercret = "";
            string normalizedUrl;
            string normalizedRequestParameters;

            OAuthBase myOAuth = new OAuthBase();
            Uri apiUrl = new Uri(Util.GetAppSettingValue("bigMingAPIUrl"));
            List<OAuth.OAuthBase.QueryParameter> lstToken = Util.GetQueryParameters(resultAccessToken);
            string[] arrResult1 = resultAccessToken.Split('&');
            if (arrResult1.Length > 1)
            {
                token = arrResult1[0].Substring(arrResult1[0].IndexOf('=') + 1);
                tokenSercret = arrResult1[1].Substring(arrResult1[1].IndexOf('=') + 1);
            }
            string signature = myOAuth.MingSignature(apiUrl, Util.GetAppSettingValue("mingConsumerKey"), Util.GetAppSettingValue("mingConsumerSecret"), "", "GET", timeStamp, nonce, "",
                HttpUtility.HtmlDecode(token), HttpUtility.HtmlDecode(tokenSercret), OAuth.OAuthBase.SignatureTypes.HMACSHA1,
                out normalizedUrl, out normalizedRequestParameters);

            string strGenURL = normalizedUrl + "?" + normalizedRequestParameters + "&oauth_signature=" + myOAuth.UrlEncode(signature);
            getData(strGenURL);
        }
        protected virtual void getData(string url)
        {
            try
            {
                string result = string.Empty;

                WebRequest wrq = WebRequest.Create(url);
                WebResponse wrs = wrq.GetResponse();

                StreamReader strdr = new StreamReader(wrs.GetResponseStream(), Encoding.UTF8);
                result = strdr.ReadToEnd();
                strdr.Close();
                wrs.Close();
                var o = VietIDObject.ConvertMingJson(result);
                var UDisplay = string.Empty;
                var ULink = string.Empty;
                string UClick = string.Empty;
                string UrlRound = "#";
                if (!String.IsNullOrEmpty(o.user.email))
                {
                    MembersObject u = MembersCache.Members_GetByEmail(o.user.email);
                    if (u == null)
                    {
                        u = new MembersObject();
                        u.Member_Name = o.user.username;
                        u.Member_Email = o.user.email;
                        u.Member_Status = (int)MemberStatus.IsNoRegister;
                        u.Member_InRound = (int)MemberRound.NoRound;
                        u.Member_Birthday = DateTimeFunctions.ValidDateTime(o.user.birthday);
                        u.Member_RegisterDate = DateTime.Now;
                        u.Member_ID = MembersController.Members_Insert(u);
                    }
                    o.user.status = u.Member_Status;
                    o.user.round = u.Member_InRound;
                    o.user.memberId = u.Member_ID;

                    if (u.Member_Status == (int)MemberStatus.IsPublished && RefCache.Ref_GetLockEditStatus() && u.Member_InRound >= RefCache.Ref_GetCurrentRound())
                    {
                        UDisplay = "Sửa thông tin";
                        ULink = "/sua-thong-tin.htm";
                        // chua dc set vong thi UrlRound ve vong 1
                    }
                    else if (u.Member_Status == (int)MemberStatus.IsNoRegister && RefCache.Ref_GetLockRegisterStatus())
                    {
                        UDisplay = "Đăng ký dự thi";
                        ULink = "/dang-ky-du-thi.htm";
                    }
                    if (u.Member_Status == (int)MemberStatus.IsPublished)
                    {
                        if (u.Member_InRound == (int)MemberRound.NoRound)
                            u.Member_InRound = (int)MemberRound.Round1;
                        UrlRound = UrlHelpers.MembersDetails(u.Member_ID, u.Member_Email, u.Member_InRound);
                    }
                    //
                }
                string userDataString = o.user.username + "|" + o.user.email + "|" + o.user.full_name + "|" + o.user.status + "|" + o.user.round + "|" + o.user.memberId;
                HttpCookie authCookie = FormsAuthentication.GetAuthCookie(o.user.username, true);
                FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);
                FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, DateTime.Now, DateTime.Now.AddMonths(1), ticket.IsPersistent, userDataString);
                authCookie.Value = FormsAuthentication.Encrypt(newTicket);
                Response.Cookies.Add(authCookie);

                // luu vao session
                HttpContext.Current.Session[Const.AuthenticationSessionName] = userDataString;
                // luu vao session

                //Response.Write("<script>parent.reload();</script>");
                Response.Write("<script>parent.closeLoginBox({'UName':'" + o.user.username + "','UEmail':'" + o.user.email + "','ULink':'" + ULink + "' ,'UDisplay':'" + UDisplay + "','UClick':'" + UClick + "','UrlRound':'" + UrlRound + "'});</script>");
            }
            catch
            {
                Response.Write("<script>parent.reload();</script>");
            }
        }
    }
}